<?php

declare(strict_types=1);

namespace App\Controller;

use App\Constants\ErrorCode;
use App\Library\Common;
use App\Model\data\CurrentShopData;
use App\Model\DeliveryRule;
use App\Model\DeliverySendOrder;
use App\Model\FlyOrder;
use App\Model\ShopSendAddress;
use App\Service\DeliverySendService;
use App\Service\EsService;
use App\Service\NotifyLog\ExpressLogService;
use App\Service\ShopSendAddressService;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Validation\Rule;

class DeliverySendController extends AbstractController
{
    const DELIVERY=[
        'yuantong'=>'圆通速递',
        'yunda'=>'韵达快递',
        'zhongtong'=>'中通快递',
        'shentong'=>'申通快递',
        'jtexpress'=>'极兔速递',
        'shunfeng'=>'顺丰速运',
        'jd'=>'京东物流',
        'youzhengguonei'=>'邮政快递包裹',
        'debangkuaidi'=>'德邦快递',
        'ems'=>'EMS',
    ];
    const DAYTYPE=[
        '今天',
        '明天',
        '后天',
    ];

//订阅类型 1 发货  2退货  3维修  4退货退款  5补发
    const ORDERTYPE=[
        '1',
        '2',
        '3',
        '4',
        '5',
    ];

    //订阅物流类型 1 发货  2同城配送
    const SENDTYPE=[
        '1',
        '2',
    ];

    /**
     * @Inject
     * @var DeliverySendService
     * */

    private $deliverySendService;


    /**
     * 物流等信息
     * @Inject
     * @var ExpressLogService
     */
    private  $expressLogService;

    /**
     * @Inject
     * @var ShopSendAddressService
     */
    private $sendAddress;

    //    全部快递公司
    public function delivery_list()
    {
        return $this->jsonResponse->success(self::DELIVERY,'返回');
    }

//    订阅回调，接收回调进行处理
    public function call_back()
    {
        $params  =$this->request->all();
//        $type =$this->request->input('type',1);
        Db::beginTransaction();
        $res = false;
        try {
            $param = json_decode($params['param'],true);
            if(isset($param['lastResult'])){
                $res = $this->deliverySendService->log($param['lastResult'],'');
            }
            if($res==true){
                Db::commit();
                return $this->response->json([
                    "result"=> true,
                    "returnCode"=> "200",
                    "message"=> "成功"
                ]);
            }else{
                Db::rollBack();
                return $this->response->json([
                    "result"=> false,
                    "returnCode"=> "200",
                    "message"=> "失败"
                ]);
            }
        } catch (\Throwable $exception) {
            var_dump($exception->getMessage());
            Db::rollBack();
            return  $this->response->json([
                "result"=> false,
                "returnCode"=> "200",
                "message"=> "失败"
            ]);
        }

    }

//订阅物流
    public function poll()
    {
        $request_p = $this->request->inputs(['num','com','order_sn','order_type','send_type']);
        $shop_info =  CurrentShopData::getData();
        $shop_id =  $shop_info->id;
        $this->validation($request_p,
            [
                'order_type'=>[
                    'required',
                    Rule::in(self::ORDERTYPE),
                ],
                'send_type'=>[
                    'required',
                    Rule::in(self::SENDTYPE),
                ],
                'num'=>[
                    'required',
                    'string',
                    'max:100',
                    Rule::unique('fly_poll_log','num')
                        ->where('order_sn',$request_p['order_sn'])
                        ->where('num',$request_p['num'])
                ],
                'com'=>[
                    'required',
                    Rule::in(array_keys(self::DELIVERY)),
                ],
                'order_sn'=>[
                    'required',
                    'string',
                    Rule::exists('fly_order','order_sn')
                        ->where('shop_id',$shop_id)
                        ->where('order_type',$request_p['order_type']),
                ]
            ],
        );
        //参数设置
        $param = array (
            'company' => $request_p['com'],          //快递公司编码
            'number' => $request_p['num'],    //快递单号
            'from' => '',                     //出发地城市
            'to' => '',                       //目的地城市
            'parameters' => array (
                'salt' => 'test',                 //加密串
                'resultv2' => '1',            //行政区域解析
                'autoCom' => '0',             //单号智能识别
                'interCom' => '0',            //开启国际版
                'departureCountry' => '',     //出发国
                'departureCom' => '',         //出发国快递公司编码
                'destinationCountry' => '',   //目的国
                'destinationCom' => '',       //目的国快递公司编码
                'phone' => ''                 //手机号
            )
        );

        Db::beginTransaction();
        try {
            $address_info  = $this->sendAddress->info(0,$shop_id);
            $res = $this->deliverySendService->poll($param,$request_p['order_sn'],$address_info);
            $order_info = FlyOrder::query()->where('order_sn',$request_p['order_sn'])->first();
            $this->expressLogService->insert_log(intval($order_info->order_id),intval($order_info->user_id),intval($shop_id),1,1);
            if($res&&isset($res['result'])&&$res['result']==true){
//            if(true){
                $res = $this->deliverySendService->check_poll($request_p);
                if($res){
                   Db::commit();

                    return $this->jsonResponse->success($res,'订阅成功');
                }else{
                    Db::rollBack();
                    return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'订阅失败');
                }
            }else{
                Db::rollBack();
                return $this->jsonResponse->error(ErrorCode::SERVER_ERROR,'订阅失败-'.$res['returnCode'].':'.$res['message']);
            }
        } catch (\Throwable $exception) {
            Db::rollBack();
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'订阅失败.'.$exception->getMessage());
        }
    }

    public function check()
    {
        $check_kds =$this->request->input('check_kds','');
        $from =$this->request->input('from','');
        $to =$this->request->input('to','');
        if(!$from||!$to){
            return $this->jsonResponse->error(0,'缺少参数');
        }
        if($check_kds==''){
            $check_kds = implode('&',array_keys(self::DELIVERY));
        }
        try {
            $res = $this->deliverySendService->check($from,$to,$check_kds);
            if($res){
                if (isset($res['data'])){
                    return $this->jsonResponse->success($res['data'],'查询成功');
                }else{
                    $res = [
                        "result"=> true,
                        "returnCode"=> "200",
                        "message"=> "成功",
                        "data"=> [
                            [
                            "com"=> "shunfeng",
                            "lsCheck"=> true,
                            "lsCount"=> "41125",
                            "pjCheck"=> true,
                            "pjCount"=> "11838",
                            "xzqCode"=> "440300000000",
                            "xzqFullName"=> "广东,深圳市",
                            ],
                            [
                                "com"=> "yunda",
                                "lsCheck"=> true,
                                "lsCount"=> "41125",
                                "pjCheck"=> true,
                                "pjCount"=> "11838",
                                "xzqCode"=> "440300000000",
                                "xzqFullName"=> "广东,深圳市",
                            ],
                        ]
                    ];
                    foreach($res['data'] as $key=>$value){
                        $res['data'][$key]['name']  = SELF::DELIVERY[$value['com']];
                    }
                    return $this->jsonResponse->success($res,'查询成功');
                }

            }else{
                return $this->jsonResponse->error(ErrorCode::SERVER_ERROR,'查询失败-');
            }
        } catch (\Throwable $exception) {
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'查询失败.'.$exception->getMessage());
        }
    }
    public function check_order_send()
    {
        $order_id=  $this->request->input('order_id');
        try {
            return $this->jsonResponse->success($this->deliverySendService->get_send_order($order_id),'获取成功');
        } catch (\Throwable $exception) {
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'获取失败.'.$exception->getMessage());
        }
        return $this->jsonResponse->success([],'返回');
    }
    public function check_price()
    {
       $request_params =  $this->request->inputs(['from','to','weight','com']);
        $this->validation($request_params,
            [
                'from'=>'required|string',
                'to'=>'required|string',
                'weight'=>'required|numeric|max:100|min:0',
                'com'=>[
                    'required',
                    Rule::in(array_keys(self::DELIVERY)),
                ],
            ],
        );
        try {
            $res =  $this->deliverySendService->check_price($request_params);
            if($res){
                return $this->jsonResponse->success($res,'获取成功');
            }else{
                return $this->jsonResponse->error(ErrorCode::SERVER_ERROR,'获取失败-');
            }
        } catch (\Throwable $exception) {
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'获取失败.'.$exception->getMessage());
        }
    }

//    商家取消快递订单
    public function cancel(){
        $request_params  =  $this->request->inputs(['delivery_order_id','task_id']);
        $this->validation($request_params,
            [
                'delivery_order_id'=>[
                    'required',
                    Rule::exists('fly_delivery_send_order','delivery_order_id')->whereNull('deleted_at'),
                ],
                'task_id'=>[
                    'required',
                    'integer',
                    Rule::exists('fly_delivery_send_order','task_id')->whereNull('deleted_at'),
                ],

            ],
            );
        $delivery_order_id = $request_params['delivery_order_id'];
        $task_id =  $request_params['task_id'];
        try {
            $res =  $this->deliverySendService->cancel(intval($delivery_order_id),$task_id);
            if($res&&$res['result']==true){
                return $this->jsonResponse->success($res,'取消成功');
            }else{
                return $this->jsonResponse->error(ErrorCode::SERVER_ERROR,'取消失败-'.$res['returnCode'].':'.$res['message']);
            }
        } catch (\Throwable $exception) {
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'取消失败.'.$exception->getMessage());
        }
    }

//    c端发起快递订单
    public function c_send(){
        $request_params  =  $this->request->inputs(['com','send_address_id','order_id','link_name','phone','address','day_type','start_time','end_time','remark']);
        $shop_info = CurrentShopData::getData();
        $this->validation($request_params,
            [
                'com'=>[
                    'required',
                    Rule::in(array_keys(self::DELIVERY)),
                ],
                'send_address_id'=>[
                    'required',
                    'integer',
                    Rule::exists('fly_shop_send_address','id')->whereNull('deleted_at'),
                ],
                'day_type'=>[
                    'required',
                    'string',
                    Rule::in(self::DAYTYPE),
                ],

                'order_id'=>[
                    'required',
                    'integer',
                    Rule::exists('fly_order','order_id')
                        ->where('shop_id',$shop_info->id)
                        ->where('order_status',2)
                        ->where('delivery_type',1)
                        ->where('delivery_id',0),
                ],
                'link_name'=>"required|string|max:100",
                'remark'=>"string|max:100",
                'phone'=>"required|string|max:100",
                'address'=>"required|string|max:150",
                'start_time'=>[
                    'string',
                    'date_format:"H:i"',
                ],
                'end_time'=>[
                    'string',
                    'date_format:"H:i"',
                ],
            ],
        );
        $order_info = FlyOrder::query()->find($request_params['order_id']);
        $address_info  = $this->sendAddress->info(intval($request_params['send_address_id']));
        $params =[
            'com'=>$request_params['com'],
            'sendManName'=> $address_info['link_name'],
            'sendManMobile'=>$address_info['phone'],
            'sendManPrintAddr'=>$address_info['street_str'].$address_info['address_info'],

            'recManName'=>$order_info->link_name,
            'recManMobile'=> $order_info->phone,
            'recManPrintAddr'=> $order_info->address,
            'remark'=> $request_params['remark'],

            'dayType'=> $request_params['day_type'],
            'pickupStartTime'=> $request_params['start_time'],
            'pickupEndTime'=> $request_params['end_time'],
        ];
        if($request_params['day_type']=='今天'){
            $send_date = date('Y-m-d');
        }elseif($request_params['day_type']=='明天'){
            $send_date = date('Y-m-d',time()+3600*24);
        }else{
            $send_date = date('Y-m-d',time()+3600*24*2);
        }
        Db::beginTransaction();
        try {
            $res =  $this->deliverySendService->c_send($params);
            if($res){
                if($res['code']!=200){
                    Db::rollBack();
                    return $this->jsonResponse->error(ErrorCode::SERVER_ERROR,'下单失败-'.$res['message']);
                }else{
                    $send_order  = [
                        'service_type'=>1,
                        'delivery_type'=>$params['com'],
                        'delivery_name'=>self::DELIVERY[$params['com']],
                        'type'=>1,
                        'is_poll'=>0,
                        'delivery_order_id'=>$res['data']['orderId'],
                        'order_id'=>$order_info->order_id,
                        'order_sn'=>$order_info->order_sn,
                        'task_id'=>$res['data']['taskId'],
                        'created_at'=>date('Y-m-d H:i:s'),
                        'from_address'=>$params['sendManPrintAddr'],
                        'from_name'=>$params['sendManName'],
                        'from_phone'=>$params['sendManMobile'],
                        'to_address'=>$params['recManPrintAddr'],
                        'to_name'=>$params['recManName'],
                        'to_phone'=>$params['recManMobile'],
                        'send_date'=> $send_date,
                        'start_time'=> $request_params['start_time'],
                        'end_time'=> $request_params['end_time'],
                        'remark'=> $request_params['remark'],
                    ];
                    $delivery_id  = DeliverySendOrder::query()->insertGetId(Common::filter_null($send_order));
                    Db::commit();
                    return $this->jsonResponse->success($res,'下单成功');
                }

            }else{
                Db::rollBack();
                return $this->jsonResponse->error(ErrorCode::SERVER_ERROR,'下单失败-');
            }
        } catch (\Throwable $exception) {
            Db::rollBack();
            return $this->jsonResponse->error(ErrorCode::SERVER_ERROR,'下单失败-'.$exception->getMessage());
        }
    }

    //   c端取消快递订单
    public function c_cancel(){
        $order_sn = $this->request->input('order_sn','');
        $shop_info =  CurrentShopData::getData();
        $shop_id =  $shop_info->id;
        $msg = $this->request->input('msg','暂时不邮寄了');
        $this->validation([
            'order_sn'=>$order_sn,
            'msg'=>$msg
        ],
            [
                'msg'=>[
                    'required',
                    'string',
                    'max:100',
                ],
                'order_sn'=>[
                    'required',
                    'string',
                    Rule::exists('fly_order','order_sn')
                        ->where('shop_id',$shop_id)
                        ->where('order_status',2)
                        ->where('delivery_id','!=',0)
                        ->where('delivery_type',1),
                ]
            ],
            );
        Db::beginTransaction();
        try {
            $res =  $this->deliverySendService->c_cancel($order_sn,$msg);
            if($res==true){
                Db::commit();
                return $this->jsonResponse->success($res,'取消成功');
            }else{
                Db::rollBack();
                return $this->jsonResponse->error(ErrorCode::SERVER_ERROR,'取消失败-');
            }
        } catch (\Throwable $exception) {
            Db::rollBack();
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'取消失败.'.$exception->getMessage());
        }
    }

//    //    发起快递订单
//    public function add(){
//        $order_sn  =  $this->request->input('order_sn');
//        $shop_info = CurrentShopData::getData();
//        $this->validation(['order_sn'=>$order_sn],
//            [
//                'order_sn'=>[
//                    'required',
//                    'integer',
//                    Rule::exists('fly_order','order_id')
//                        ->where('shop_id',$shop_info->id)
//                        ->where('order_status',2)
//                        ->where('delivery_type',1)
//                        ->where('delivery_id',0),
//                ]
//            ],
//            );
//        $order_info = FlyOrder::query()->where('order_sn',$order_sn)->first();
//        $order_id = 100094564564;
//        $param = array (
//            'kuaidicom' => 'jd',              // 快递公司的编码
//            'recManName' => '收件人',             // 收件人姓名
//            'recManMobile' => '18768850763',           // 收件人手机号
//            'recManPrintAddr' => '广东深圳市深圳市南山区科技南十二路2号金蝶软件园B10',        // 收件人所在完整地址
//            'sendManName' => '寄件人',            // 寄件人姓名
//            'sendManMobile' => '18768850764',          // 寄件人的手机号
//            'sendManPrintAddr' => '广东深圳市深圳市南山区科技南十二路2号金蝶软件园B10',       // 寄件人所在的完整地址
//            'callBackUrl' => 'http://api.kuaidi100.com/',            // callBackUrl订单信息回调，默认仅支持http
//            'cargo' => '笔记本',                  // 物品名称
//            'payment' => 'SHIPPER',         // 支付方式，SHIPPER: 寄付（默认）。不支持到付
//            'weight' => '0',              // 物品总重量KG，不需带单位
//            'remark' => '测试',             // 备注
//            'salt' => 'kd100',                   // 签名用随机字符串
//            'dayType' => '今天',             // 预约日期，例如：今天/明天/后天
//            'pickupStartTime' => '09:00',        // 预约起始时间（HH:mm），例如：09:00
//            'pickupEndTime' => '10:00',          // 预约截止时间（HH:mm），例如：10:00
//            'valinsPay' => null             // 保价额度，单位：元
//        );
//        try {
//            $res =  $this->deliverySendService->send($param);
//            if($res&&$res['result']==true){
//                $send_order  = [
//                    'service_type'=>1,
//                    'delivery_type'=>$param['kuaidicom'],
//                    'delivery_name'=>self::DELIVERY[$param['kuaidicom']],
//                    'type'=>1,
//                    'is_poll'=>0,
//                    'delivery_order_id'=>$res['data']['orderId'],
//                    'order_id'=>$order_info->order_id,
//                    'order_sn'=>$order_info->order_sn,
//                    'task_id'=>$res['data']['taskId'],
//                    'created_at'=>date('Y-m-d H:i:s'),
//                    'from_address'=>$param['sendManPrintAddr'],
//                    'from_name'=>$param['sendManName'],
//                    'from_phone'=>$param['sendManMobile'],
//                    'to_address'=>$param['recManPrintAddr'],
//                    'to_name'=>$param['recManName'],
//                    'to_phone'=>$param['recManMobile'],
//                ];
//                DeliverySendOrder::query()->insert($send_order);
//                //订阅
//                $poll_param = array (
//                    'company' => $param['kuaidicom'],          //快递公司编码
//                    'number' => $res['data']['orderId'],    //快递单号
//                    'from' => $param['sendManPrintAddr'],                     //出发地城市
//                    'to' => $param['recManPrintAddr'],                       //目的地城市
//                    'parameters' => array (
//                        'callbackurl' => 'http://192.168.1.33:62002/api/v1/delivery_send/call_back',          //回调地址
//                        'salt' => 'test',                 //加密串
//                        'resultv2' => '1',            //行政区域解析
//                        'autoCom' => '0',             //单号智能识别
//                        'interCom' => '0',            //开启国际版
//                        'departureCountry' => '',     //出发国
//                        'departureCom' => '',         //出发国快递公司编码
//                        'destinationCountry' => '',   //目的国
//                        'destinationCom' => '',       //目的国快递公司编码
//                        'phone' => ''                 //手机号
//                    )
//                );
//                $this->deliverySendService->poll($poll_param);
//                return $this->jsonResponse->success($res,'下单成功');
//            }else{
//                return $this->jsonResponse->error(ErrorCode::SERVER_ERROR,'下单失败-'.$res['returnCode'].':'.$res['message']);
//            }
//        } catch (\Throwable $exception) {
//            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'下单失败.'.$exception->getMessage());
//        }
//    }


/***
 *                                         ,s555SB@@&
 *                                      :9H####@@@@@Xi
 *                                     1@@@@@@@@@@@@@@8
 *                                   ,8@@@@@@@@@B@@@@@@8
 *                                  :B@@@@X3hi8Bs;B@@@@@Ah,
 *             ,8i                  r@@@B:     1S ,M@@@@@@#8;
 *            1AB35.i:               X@@8 .   SGhr ,A@@@@@@@@S
 *            1@h31MX8                18Hhh3i .i3r ,A@@@@@@@@@5
 *            ;@&i,58r5                 rGSS:     :B@@@@@@@@@@A
 *             1#i  . 9i                 hX.  .: .5@@@@@@@@@@@1
 *              sG1,  ,G53s.              9#Xi;hS5 3B@@@@@@@B1
 *               .h8h.,A@@@MXSs,           #@H1:    3ssSSX@1
 *               s ,@@@@@@@@@@@@Xhi,       r#@@X1s9M8    .GA981
 *               ,. rS8H#@@@@@@@@@@#HG51;.  .h31i;9@r    .8@@@@BS;i;
 *                .19AXXXAB@@@@@@@@@@@@@@#MHXG893hrX#XGGXM@@@@@@@@@@MS
 *                s@@MM@@@hsX#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&,
 *              :GB@#3G@@Brs ,1GM@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@B,
 *            .hM@@@#@@#MX 51  r;iSGAM@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@8
 *          :3B@@@@@@@@@@@&9@h :Gs   .;sSXH@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@:
 *      s&HA#@@@@@@@@@@@@@@M89A;.8S.       ,r3@@@@@@@@@@@@@@@@@@@@@@@@@@@r
 *   ,13B@@@@@@@@@@@@@@@@@@@5 5B3 ;.         ;@@@@@@@@@@@@@@@@@@@@@@@@@@@i
 *  5#@@#&@@@@@@@@@@@@@@@@@@9  .39:          ;@@@@@@@@@@@@@@@@@@@@@@@@@@@;
 *  9@@@X:MM@@@@@@@@@@@@@@@#;    ;31.         H@@@@@@@@@@@@@@@@@@@@@@@@@@:
 *   SH#@B9.rM@@@@@@@@@@@@@B       :.         3@@@@@@@@@@@@@@@@@@@@@@@@@@5
 *     ,:.   9@@@@@@@@@@@#HB5                 .M@@@@@@@@@@@@@@@@@@@@@@@@@B
 *           ,ssirhSM@&1;i19911i,.             s@@@@@@@@@@@@@@@@@@@@@@@@@@S
 *              ,,,rHAri1h1rh&@#353Sh:          8@@@@@@@@@@@@@@@@@@@@@@@@@#:
 *            .A3hH@#5S553&@@#h   i:i9S          #@@@@@@@@@@@@@@@@@@@@@@@@@A.
 *
 *
 *    妈妈，再爱我一次！
 */
}
